package cn.edu.scau.cmi.ema.controller.rest;

import org.springframework.stereotype.Controller;

import java.util.List;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.io.IOException;

import com.google.gson.Gson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


import cn.edu.scau.cmi.ema.domain.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiPsonService;
import cn.edu.scau.cmi.ema.controller.base.CmiEmaController;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.service.*;

import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.WebDataBinder;

@Controller("PictureRestController")
public class PictureRestController extends CmiEmaController {

	/**
	 * Create a new Picture entity
	 * 
	 */
	@RequestMapping(value = "/newPicture", method = RequestMethod.POST)
	@ResponseBody
	public Object newPicture(@RequestBody Picture picture) {
		pictureService.savePicture(picture);
		return JSONObject.parse(cmiPsonService.toJsonString(pictureDAO.findPictureByPrimaryKey(picture.getId()), 2));
	}

	@RequestMapping(value = "/restNewPicture", method = RequestMethod.POST)
	@ResponseBody
	public Object restNewPicture(@RequestBody String pictureJson) {
		Picture picture = new Gson().fromJson(pictureJson, Picture.class);
		appendReferences(picture);
		pictureService.savePicture(picture);
		return JSONObject.parse(cmiPsonService.toJsonString(pictureDAO.findPictureByPrimaryKey(picture.getId()), 2));
	}

	@RequestMapping(value = "/savePicture", method = RequestMethod.PUT)
	@ResponseBody
	public Picture savePicture(@RequestBody Picture picture) {
		pictureService.savePicture(picture);
		return pictureDAO.findPictureByPrimaryKey(picture.getId());
	}

	@RequestMapping(value = "/restSavePicture", method = RequestMethod.PUT)
	@ResponseBody
	public Object restSavePicture(@RequestBody String pictureJson) {
		Picture picture = new Gson().fromJson(pictureJson, Picture.class);
		appendReferences(picture);
		CmiPsonService cmiPsonService = new CmiPsonService();
		pictureService.savePicture(picture);
		return JSONObject.parse(cmiPsonService.toJsonString(pictureDAO.findPictureByPrimaryKey(picture.getId()), 1));
	}

	@RequestMapping(value = "/restDeletePicture/{pictureId}", method = RequestMethod.DELETE)
	@ResponseBody
	public void restDeletePicture(@PathVariable Integer pictureId) {
		Picture picture = pictureDAO.findPictureByPrimaryKey(pictureId);
		pictureService.deletePicture(picture);
	}

	@RequestMapping(value = "/restConfirmDeletePictures")
	@ResponseBody
	public Object restConfirmDeletePictures(@RequestBody Set<Integer> deletePicturesIds) {
		Set<Picture> deletePictures = pictureDAO.findPicturesByIds(deletePicturesIds);
		Set<Picture> referencedPictures = pictureService.loadReferencePictures(deletePictures);
		deletePictures.removeAll(referencedPictures);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("referencedEntitys", referencedPictures);
		jsonObject.put("deleteEntitys", deletePictures);
		return JSONObject.parse(jsonObject.toJSONString());
	}

	@RequestMapping("/restDeletePictures")
	@ResponseBody
	public Object restDeletePictures(@RequestBody Set<Picture> deletePictures) {
		Iterator<Picture> iterator = deletePictures.iterator();
		while (iterator.hasNext()) {
			Picture currentPicture = iterator.next();
			pictureService.deletePicture(currentPicture);
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("url", "listPictures");
		return JSONObject.parse(jsonObject.toJSONString());
	}
	// loadself

	@RequestMapping(value = "/restLoadPicture/{pictureId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadPicture(@PathVariable Integer pictureId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(pictureDAO.findPictureByPrimaryKey(pictureId), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadPictureEvent/{pictureId}/event", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadPictureEvent(@PathVariable Integer pictureId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(
				cmiPsonService.toPsonString(pictureDAO.findPictureByPrimaryKey(pictureId).getEvent(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadPictureFood/{pictureId}/food", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadPictureFood(@PathVariable Integer pictureId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(
				cmiPsonService.toPsonString(pictureDAO.findPictureByPrimaryKey(pictureId).getFood(), 2, cmiPagination));
	}
	// loadReferenceds
	// TODO loadReferencedsPson，这个方法有一些问题，待修复

	public void appendReferences(Picture picture) {

		Event event = picture.getEvent();
		if (event != null)
			picture.setEvent(eventService.findEventByPrimaryKey(event.getId()));

		Food food = picture.getFood();
		if (food != null)
			picture.setFood(foodService.findFoodByPrimaryKey(food.getId()));

	}

	@RequestMapping(value = "/restGetPictureEvent/{pictureId}/event", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetPictureEvent(@PathVariable Integer pictureId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(
				cmiPsonService.toPsonString(pictureDAO.findPictureByPrimaryKey(pictureId).getEvent(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetPictureFood/{pictureId}/food", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetPictureFood(@PathVariable Integer pictureId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(
				cmiPsonService.toPsonString(pictureDAO.findPictureByPrimaryKey(pictureId).getFood(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restListPictures", method = RequestMethod.GET)
	@ResponseBody
	public Object restListPictures() {
		return JSONObject.parse(cmiPsonService.toJsonString(pictureService.loadPictures(), 2));
	}

	@RequestMapping(value = "/restListPicturesPost", method = RequestMethod.POST)
	@ResponseBody
	public Object restListPicturesPost(@RequestBody CmiPagination cmiPagination) {

		CmiPsonService cmiPsonService = new CmiPsonService();
		cmiPagination = picturePaginationService.updateAppPagination(cmiPagination);
		int startResult = (cmiPagination.getCurrentPagination() - 1) * cmiPagination.getPaginationSize();

		Set<Picture> pictures = pictureDAO.findAllPictures(startResult, cmiPagination.getPaginationSize());
		String pictureString = cmiPsonService.toPsonString(pictures, 2, cmiPagination);

		return JSONObject.parse(pictureString);
	}

	@RequestMapping("/pictureSelectBox")
	@ResponseBody
	public JSONObject pictureSelectBox(@RequestParam(required = false) String searchTable,
			@RequestParam(required = false) Set<Integer> searchValue, // 杨宏宇2019-9-10：searchValue是在selectpage.js的616行定义，如果要修改searchValue的名称，1.可以修改在selectpage.js修改；2.可以
																		// @RequestParam(value="searchValue", required =
																		// false) Set<Integer> someName
			@RequestParam(required = false, defaultValue = "10") int paginationSize,
			@RequestParam(required = false, defaultValue = "1") int pageNumber,
			@RequestParam(value = "qWord[]", required = false) String queryword,
			@RequestParam(required = false) String selectItem) throws IOException {
		Set entitySet = null;
		Integer count = 0;

		// 初始化原始值

		if (searchValue != null) {
			switch (searchTable) {
			// 外键
			case "Event":
				entitySet = eventService.loadEventsByIdSet(searchValue);
				break;
			case "Food":
				entitySet = foodService.loadFoodsByIdSet(searchValue);
				break;

			// 被引用键
			}
			// 没有测试，深度需要多少？？？
			String jsonData = cmiPsonService.toJsonString(entitySet, 1);
			JSONArray jsonArray = new JSONArray();
			jsonArray = (JSONArray) JSON.parse((String) jsonData);

			JSONObject jsonObject = new JSONObject();
			jsonObject.put("list", jsonArray);
			jsonObject.put("totalRow", entitySet.size());
			return jsonObject;
		}

		// 不根据关键字进行搜索
		if (queryword == null || queryword.trim() == "") {
			switch (selectItem) {
			// 外键
			case "Event":
				entitySet = eventDAO.findAllEvents((pageNumber - 1) * paginationSize, paginationSize);
				count = eventService.countEvents();
				break;
			case "Food":
				entitySet = foodDAO.findAllFoods((pageNumber - 1) * paginationSize, paginationSize);
				count = foodService.countFoods();
				break;

			// 被引用键
			}
		} else {
			switch (selectItem) {
			// 外键
			case "Event":
				entitySet = eventDAO.findEventByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = eventService.countEventsByName(queryword);
				break;
			case "Food":
				entitySet = foodDAO.findFoodByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = foodService.countFoodsByName(queryword);
				break;

			// 被引用键
			}
		}
		/**
		 * 将Json数据转换成jsonArray形式，需要通过pson方式进行转换，然后再转换成JsonArray。因为存在懒加载
		 * 没有直接使用CmiPsonService中的fromJson方法是因为，fromJson方法会将int类型的直接转换成double类型的数据，这个问题还没有解决
		 */
		// 没有测试，深度需要多少？？？
		String jsonData = cmiPsonService.toJsonString(entitySet, 1);
		JSONArray jsonArray = new JSONArray();
		jsonArray = (JSONArray) JSON.parse((String) jsonData);

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("list", jsonArray);
		jsonObject.put("paginationSize", paginationSize);
		jsonObject.put("pageNumber", pageNumber);
		jsonObject.put("totalRow", count);
		jsonObject.put("totalPaginations",
				count % paginationSize == 0 ? count / paginationSize : count / paginationSize + 1);
		return jsonObject;
	}
}
